package cn.edu.cqupt.service.impl;

import cn.edu.cqupt.controller.UploadController;
import cn.edu.cqupt.dao.PictureDao;
import cn.edu.cqupt.po.Picture;
import cn.edu.cqupt.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;

/**
 * @author Andrew
 * @date 2018/1/15
 */
@Service
public class PictureServiceImpl implements PictureService {
    @Autowired
    PictureDao pictureDao;
    @Override
    public int savePicture(Picture picture) {
        return pictureDao.insertPicture(picture);
    }

    @Override
    public Picture getPicture(int id) {
        return pictureDao.selectPicturePath(id);
    }

    @Override
    public Picture removePictureFiles(Picture picture) {
        File file = new File(UploadController.ROOT_PATH + picture.getPicturePath());
        if (!file.exists() || file.delete())
            picture.setId(0);
        return picture;
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public boolean removePicture(int id) {
        Picture p = pictureDao.selectPicturePath(id);
        File file = new File(UploadController.ROOT_PATH + p.getPicturePath());
        pictureDao.deletePicture(p.getId());
        if (!file.exists() || file.delete()){
            return true;
        }
        return false;
    }
}
